<?php
	App::import('Model','Eav.AbstractField');
	class CustomField extends AbstractField
	{
		var $name = "CustomField";
		protected $fieldsetModelName = "Eav.Fieldset";
		protected $schemModels = array("Listing","Review");

		
		protected $fieldOptionModelName = "CustomFieldOption";
		var $hasMany = array(
			'CustomFieldOption'=>array(
				'className'=>'CustomFieldOption',
				'foreignKey'=>'custom_field_id',
				'dependent'=>true,
				'order' => array('sort_order'=>'ASC'),
			)
		);
		function useSeparateFieldOption()
		{
			return true;
		}

		function useFieldset()
		{
			return true;
		}
		
		function getGroupTypes()
		{
			$group = array('edit'=>"Allow user to edit",'index'=>"Show in admin index.","add"=>"Add","advanced_search"=>"Show on advanced Search");
			return $group;
		}
		
		function initialize()
		{
			parent::initialize();
			$this->setFieldProperties('group',array('group'=>array(),'options'=>array()));
			$this->setFieldProperties("other_information", array("fieldModifier"=>"toggleSerialized"));
			$this->setFieldProperties("mask_url", array('label'=>"Mask URL",'type'=>"checkbox","group"=>array("add","edit")));
			$this->setFieldProperties("anchor_text", array('label'=>"Anchor Text",'type'=>"text","group"=>array("add","edit")));
			foreach($this->getGroupTypes() as $type =>$label)
			{
				if($type == "add")
				{
					continue;
				}
				$this->setFieldProperties($type,array('group'=>array('grid','add','edit'),'type'=>'checkbox','label'=>$label,'options'=>array(__('No'),__('Yes'))));
			}
		}
		
		function afterInitialize()
	    {
	    	parent::afterInitialize();
	    	
	    	$fieldProperties = $this->fieldProperties;
	    	foreach($fieldProperties as $field=>$properties)
	    	{
	    		if(isset($properties['options']))
	    		{
		    		foreach($properties['options'] as $value=>$label)
		    		{
		    			$newOptionList[$value] = __($label);
		    		}
		    		$this->fieldProperties[$field]['options'] = $newOptionList;
		    		if(isset($this->fieldProperties[$field]['empty']))
		    		{
		    			$this->fieldProperties[$field]['empty'] = __($this->fieldProperties[$field]['empty']);
		    		}
		    		
		    	}
		    	$newOptionList = array();
	    	}     
	    	
			
	    }
		/**
		 * set group array from fields values
		 * @param $value
		 * @param $action
		 * @param $result
		 * @param $fieldName
		 */
		function toggleSerialized($value,$action,$result,$fieldName)
		{
			if($action==self::READ && $fieldName=='group')
			{
				$value = array();
				$value[] = 'add';
				$groupFields = $this->getGroupFields();
				foreach($groupFields as $field)
				{
					if(isset($result[$this->alias][$field]) && $result[$this->alias][$field] == 1)
					{
						$value[] = $field;
					}
				}
				return $value;		 
			}
			return parent::toggleSerialized($value,$action,$result,$fieldName);
		}
		/**
		 * Reutrn name of schema fields that we will be used in group.
		 */
		function getGroupFields()
		{
			return array('index','edit');
		}
		
		function getFieldTypes()
		{
			
			$fields = array('datePicker'=>__("Date Picker"),'countrySuggestor' => __('Country'),'url'=>"URL/Website",'video'=>__("Video"));
			$fields = am(parent::getFieldTypes(),$fields);
			unset($fields['currency'],$fields['date'],$fields['datetime']);
			asort($fields,SORT_STRING);
			return $fields;
		}
		
		function afterSave($created)
		{
			$fieldsetId = $this->field('fieldset_id',array('id'=>$this->id));
			$this->getFieldsetModel()->refreshCustomFieldsCache($fieldsetId);
			return parent::aftersave($created);	
		}

		function fieldsetModelConfig($config = array())
		{
			parent::fieldsetModelConfig($config);
			$this->setFieldProperties($this->getFieldsetModel()->foreignKey,array('group'=>array('grid'),'label'=>__("Fieldset"),'empty'=>"-Select-"));
			$this->addValidationRule($this->getFieldsetModel()->foreignKey,array('rule'=>VALID_NOT_EMPTY,'required'=>true,'on'=>"create"));
		}
		/**
		 * deletes values from db for given field to be called on delete only
		 * @param unknown_type $fieldId
		 */
		private function deleteEavRecordsValues($fieldId)
		{
			$type = $this->field('type',array('id'=>$fieldId));
			$field = $this->field('name',array('id'=>$fieldId));
			$dbType = Utility::getDbFieldType($type);
			if($dbType)
			{
				$ReviewModel = cri('Review');
				$ListingModel = cri('Listing');
				$EavRecord = cri('Eav.EavRecord');
				$SubValueModel = $EavRecord->getValuesSubModel($dbType);
				$eavRecordIds =  $EavRecord->find('list',array('conditions'=>array('entity'=>array($ReviewModel->alias,$ListingModel->alias)),'fields'=>array('id')));
				if($eavRecordIds)
				{
					$e = $SubValueModel->deleteAll(array(
						$SubValueModel->alias.'.eav_record_id' => $eavRecordIds,
						$SubValueModel->alias.'.field' => $field,
						));
				}
			}
		}
		
		function beforeDelete($cascade)
		{
			$return = parent::beforeDelete($cascade);
			if($return == true)
			{
				$db =& ConnectionManager::getDataSource($this->useDbConfig);
				//begin transactions for delete Eav Records Value
				$db->begin($this);
				$this->deleteEavRecordsValues($this->id);	
			}
			return $return;
		}
		
		function beforeSave($options)
		{
			if(isset($this->data[$this->alias]['mask_url']))
			{
				$this->data[$this->alias]['other_information']['mask_url'] = $this->data[$this->alias]['mask_url'];
			}
			if(isset($this->data[$this->alias]['anchor_text']))
			{
				$this->data[$this->alias]['other_information']['anchor_text'] = $this->data[$this->alias]['anchor_text'];
			}
			return parent::beforeSave($options);
		}

		function afterDelete()
		{
			$db =& ConnectionManager::getDataSource($this->useDbConfig);
			//commit transactions for delete Eav Records Value
			$db->commit($this);
			return parent::afterDelete();
		}
		
		
		
	}
?>